home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 4621 < prev    next >
Encoding:
Internet Message Format  |  1996-08-06  |  1.6 KB

  1. Path: svnews.ubinet.ubs.com!ubszh!ubszh!jis
  2. From: ian.johnston@ubs.com (Johnston Ian (by ubsswop))
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: How to handle error in constructor
  5. Date: 31 Jan 1996 10:42:39 GMT
  6. Organization: UBS
  7. Distribution: world
  8. Message-ID: <4enh2v$plq@ubszh.fh.zh.ubs.com>
  9. References: <DLyyIM.5EG@teslab.lab.oz.au>
  10. NNTP-Posting-Host: nol2179.fh.zh.ubs.com
  11.  
  12. In article <DLyyIM.5EG@teslab.lab.oz.au>, andrew@teslab.lab.oz.au (Andrew Phillips) writes:
  13. |> I'm converting and enhancing a simple program in C to C++.  Without going
  14. |> into too much detail I have a class that represents a file on disk.  The
  15. |> contructor opens the file, but what should it do if the file cannot be
  16. |> opened?  The C program just calls fopen() tests the return value and 
  17. |> if there's an error it prints a message and exits.
  18. |> 
  19. |> In C++ I thought to set a flag in the constructor and have a member function
  20. |> that tests the flag to see if the file was opened correctly.  This seems
  21. |> rather inelegant -- I guess exceptions would be the elegant way but seem
  22. |> like overkill for such a simple program.  I've looked in several C++ books but
  23. |> error handling is given scant coverage except for exception handling.
  24. |> 
  25. |> Any suggestions would be greatly appreciated.
  26.  
  27.  
  28. 1. Set a flag in the object, as you suggest.
  29.  
  30. 2. Throw an exception.
  31.  
  32. 3. Have each member function test the FILE *, and if it is NULL, return
  33.    an error code. The object "degrades" into a safe, but do-nothing, object.
  34.  
  35. 4. Print an error message and exit.
  36.  
  37. If 4. was good enough for your simple C program, why is it not good
  38. enough for your simple C++ program?
  39.  
  40. Ian
  41.